package br.com.hstar.server.cliente;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.hstar.client.cliente.cliente.ClienteService;
import br.com.hstar.client.cliente.cliente.ClienteUI;
import br.com.hstar.model.cliente.ClienteDO;
import br.com.hstar.model.cliente.TipoClienteDO;
import br.com.hstar.server.DozerHelper;
import br.com.hstar.server.DozerUtility;
import br.com.hstar.server.HibernateUtility;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ClienteServiceImpl extends RemoteServiceServlet implements ClienteService {

	public void saveOrUpdate(ClienteUI objUI) {
		ClienteDO objDO = (ClienteDO) DozerUtility.getMapper().map(objUI, ClienteDO.class);
		if(objUI.getTipoCliente() != null && objUI.getTipoCliente().getId() != null) {
			objDO.setTipoCliente(getTipoCliente(objUI.getTipoCliente().getId()));
		}
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();
		
		if(objUI.getId() != null) {
			sessao.update(objDO);
		} else {
			sessao.save(objDO);
		}

		transaction.commit();
		sessao.close();
	}
	
	public List listAll() {
		Session sessao = HibernateUtility.getSession();
		Criteria select = sessao.createCriteria(ClienteDO.class);
		ArrayList objetos = (ArrayList)select.list();
		sessao.close();
		
		return DozerHelper.mapList(
				DozerUtility.getMapper(), 
				objetos, 
				ClienteUI.class);
	}
	
	public ClienteUI retrieveById(Long id) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(ClienteDO.class);
		cri.add(Restrictions.eq("id", id));
		ClienteDO objDO = (ClienteDO) cri.uniqueResult();
		sessao.close();
				
		ClienteUI objUI = (ClienteUI) DozerUtility.getMapper().map(objDO, ClienteUI.class);
		
	  	return objUI;
	}
	
	public void delete(Long id) {
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();

			Criteria cri = sessao.createCriteria(ClienteDO.class);
			cri.add(Restrictions.eq("id", id));
			ClienteDO objDO = (ClienteDO) cri.uniqueResult();
			sessao.delete(objDO);

		transaction.commit();
		sessao.close();
	}
	
	public TipoClienteDO getTipoCliente(Long id) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(TipoClienteDO.class);
		cri.add(Restrictions.eq("id", id));
		TipoClienteDO objDO = (TipoClienteDO) cri.uniqueResult();
		sessao.close();
				
		//ClienteUI objUI = (ClienteUI) DozerUtility.getMapper().map(objDO, ClienteUI.class);
		
	  	return objDO;
	}
}
